<html>
<!-- version 0.9.3 -->
<head>
<title id="title">Evoscan 2 Logworks</title>
<HTA:APPLICATION ID="porgbar" APPLICATIONNAME="progbartest">
<script language="vbscript">

	'---------------------------------
	'This is an example of progressbar
	'---------------------------------
Public x,y, MyTitle, iTimerID, KeepGoing

dim colors
colors=Array(10053171,3355545,6710835,13369395,255,10027161,3368550,16711680,153,10027008,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)


Sub Window_Onload
MyTitle = document.Title
id("ProgBarToDo").innerText = String(80, "_") & "|"  '----Fills the progressbar with gray. 
			'You can hardcode it in the body html, but it's more flexible like this
window.ResizeTo 720, 200       '----Resizing to a better size for a progressbar
x=0       '--- x will be the number of item done.
y=100     '--- y will be the number of item to do.
End Sub

Sub Go
'---FOR TEST ONLY---
Set fso = CreateObject("Scripting.FileSystemObject")
Set oof = fso.CreateTextFile("testpb.vbs", True)
oof.WriteLine "wscript.sleep WScript.Arguments(0)"  '---We'll run a sleep script so that 
			'we can see the progressbar going slowly
oof.Close
Set WshShell = CreateObject("WScript.Shell")
'----END OF TEST ONLY----

Progress(1)
	Do Until x=y
	x=x+1
	WshShell.Run "testpb.vbs 250",1,True  '----FOR TEST ONLY
		If KeepGoing = False Or window.screenTop > 10000 Then '---"window.screenTop > 10000" prevents 
					'the loop for continuing when the window is closed
		Exit Do
		End If
	Loop
Progress(0)
End Sub

Sub Progress(v)
	Select Case v
	Case 0  '---Stoping the progressbar activity---
		window.clearInterval(iTimerID)  '----Cancel the order to launch the Sub at the 500 milliseconds interval 
		iTimerID =""             '----Tells the program that iTimerID is nothing. 
					'Usefull to know if the progressbar is in activity or not.
		id("BtnGo").disabled = False       '----Allow the user to restart
		id("BtnCancel").disabled = True    '-----No need to press this button anymore
		id("BtnExit").disabled = False     '----Allow the user to exit the program
		Progress(2)            '----Update the progressbar one last time
		'MsgBox "Operation finished.",,MyTitle
		y=100
      x=0	
	Case 1  '---Starting the progressbar---
		iTimerID = window.setInterval("Progress(2)", 2000)    '----- Launching the Sub Progress 
				'every 500 milliseconds with the variable 2
		id("BtnGo").disabled = True        '----No need to press the Go button twice
		id("BtnCancel").disabled = False   '---Allow the user to stop the process
		id("BtnExit").disabled = True      '----Forbid the user to close the program before it's over
		KeepGoing = True
		Progress(2)         '---- Once started we can update it already

	Case 2  '---Updating the progressbar---
		document.Title = FormatPercent(x/y, 0) & " - " &MyTitle  '---Add a nice percentage indication of the progrss 
						'in the title bar, also visible in the desktop taskbar
		id("ProgBarText").innerText = x & "/" & y  '----Shows the number of itmed done 
						'and the number of items to do
		d = Round( x / (y/80)  ,0)   '------Formula: 80 is the width of the progressbar 
						'in number of characters
		id("ProgBarDone").innerText = String(d, "_")  '----Draws the progressing blue line indicating what is done
		If d < 80 Then   '----The bar is not full yet
		   id("ProgBarToDo").innerText = String(80-d, "_") & "|"  '----Draws the remaining grey part of the progressbar
		Else     '----If the progressbar is full, just do this...
		   id("ProgBarToDo").innerText = "|"  '---No grey part left at all
		End If			
	End Select
End Sub

Function id(o)
Set id = document.getElementById(o)
End Function

function doit
   Progress(1)
   Progress(2)
   chooseFileToConvert
end function


 Sub Sleep(MSecs) 
 Set fso = CreateObject("Scripting.FileSystemObject")
  If Fso.FileExists("sleeper.vbs")=False Then
  Set objOutputFile = fso.CreateTextFile("sleeper.vbs", True)
  objOutputFile.Write "wscript.sleep WScript.Arguments(0)"
  objOutputFile.Close
  End If
 CreateObject("WScript.Shell").Run "sleeper.vbs " & MSecs,1 , True
 End Sub

function chooseFileToConvert
' evoscan2logworks
' copyright 2012 Antoni Koziol
'
'   This program is free software: you can redistribute it and/or modify
'   it under the terms of the GNU General Public License as published by
'   the Free Software Foundation, either version 3 of the License, or
'   (at your option) any later version.
'
'   This program is distributed in the hope that it will be useful,
'   but WITHOUT ANY WARRANTY; without even the implied warranty of
'   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'   GNU General Public License for more details.
'
'   You should have received a copy of the GNU General Public License
'   along with this program.  If not, see <http://www.gnu.org/licenses/>.
'
'
' This is currenty BETA, as such, no warranty is offered.
' Most of the code is hacked to get working quickly :)





'===========================
'== User changable values ==
'===========================

'time between each log entry in the logworks file
dim ENTRY_RESOLUTION
ENTRY_RESOLUTION=.082

Dim adoCSVConnection, adoCSVRecordSet, strPathToTextfile
Dim k
dim BOT,DIR_TYPE,NUM_TYPE,VALID,SEP,VECTORS_STR,TUPLES_STR,DATA_STR,TABLE_STR,IGNORE_STR,BOT_LINE_STR,STR_TYPE_LINE,EOD
Dim DBL_QT,SIN_QT,NL

'SIENNA	#A0522D	#996633
'DARKSLATEBLUE	#483D8B	#333399
'DARKOLIVEGREEN	#556B2F	#666633
'CRIMSON	#DC143C	#CC0033
'BLUE	#0000FF	#0000FF
'DARKMAGENTA	#8B008B	#990099
'DARKSLATEGRAY	#2F4F4F	#336666
'RED	#FF0000	#FF0000
'NAVY	#000080	#000099
'DARKRED	#8B0000	#990000
'BLACK	#000000	#000000


BOT="BOT"
DIR_TYPE="-1"
NUM_TYPE="0"
STR_TYPE_LINE="1,0"
VALID="V"
SEP=","
DATA_STR="DATA"
TUPLES_STR="TUPLES"
VECTORS_STR="VECTORS"
TABLE_STR="TABLE"
NL=vbCr & vbLf
BOT_LINE_STR=DIR_TYPE & SEP & NUM_TYPE & NL &BOT
IGNORE_STR="LogID,LogEntryDate,LogEntryTime,LogEntrySeconds"
DBL_QT=""""""
SIN_QT=""""
EOD="EOD"

'Put up some warranty information...
dim warranty
warranty=msgbox("This script to convert Evoscan logs to Logworks comes with no warranty, choose OK to continue",1)
if warranty<>vbcancel then   
   



'==========================================
' Preset file chooser dialog
Dim  fileBrowserFSO,dialogFSO


'need to rename the file because the ADODB connection won't handle it later on
dim inputtemp,objFSOb,sourceFile,infilename,outfilepath,extension

sourceFile= ChooseFile()
if sourcefile <> "" then


Set objFSOb = CreateObject("Scripting.FileSystemObject")

dim tempFolder,tempFilename
tempfolder= CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2)

tempFileName="evoscan2logtemp.csv"
'inputTemp="C:\temp\evoscan2log temp.csv"
'tempFolder="C:\temp\"
Const OverwriteExisting = True
'copy the file to a temp
set sourceFile=objFSOb.GetFile(sourcefile)
strPathToTextFile=objFSOb.getparentfoldername(sourceFile)
'inputTemp= tempFolder&"\" & "evoscan2logtemp.csv"
inputTemp= strPathToTextfile &"\" & "evoscan2logtemp.csv"
'inputTemp="C:\evoscan2logtemp.csv"
objFSOb.CopyFile sourceFile, inputTemp, OverwriteExisting
'msgbox (objfsob.GetFileName(sourceFile))
'msgbox (objfsob.Getparentfoldername(sourceFile))
'save our source filename
infilename = objfsob.GetFileName(sourceFile)

extension = objfsob.GetExtensionName(sourceFile)
if extension<>"csv" then
   msgbox "'" & extension & "' is not a valid file type.  The source should be a csv file."
   wscript.quitW
end if

' Specify path to CSV file.
'strPathToTextFile = "c:\Scripts\"
'strPathToTextFile = "C:\Documents and Settings\Administrator\My Documents\Dropbox\carstuff\Scripts\"
'strPathToTextFile = "C:\Users\Antoni\Dropbox\carstuff\Scripts\"
'get our source file's path
strPathToTextFile=objFSOb.getparentfoldername(sourceFile)&"\"
outfilepath=strPathToTextfile  & objfsob.GetbaseName(sourceFile)&"_lw.dif"

' Open connection to the CSV file.
Set adoCSVConnection = CreateObject("ADODB.Connection")
Set adoCSVRecordSet = CreateObject("ADODB.Recordset")

' Open CSV file with header line.MSDASQL.1
'adoCSVConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
'adoCSVConnection.Open "Provider=MSDASQL.1;" & _
'    "Data Source=" & strPathtoTextFile & ";" & _
'    "Extended Properties=""text;HDR=YES;FMT=Delimited"""
'    inputTemp="C:\temp\evoscan2logtemp.csv"

'adoCSVConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
'    "Data Source=[" & strPathToTextFile & "\];" & _
'    "Extended Properties=""text;HDR=YES;FMT=Delimited"""
'    inputTemp="C:\temp\evoscan2logtemp.csv"


'Provider=MSDASQL; Driver={Microsoft Text Driver (*.txt; *.csv)}; DBQ=C:\path\;
dim connectionString 
connectionString= "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" & strPathToTextfile & "\;"
adoCSVConnection.open connectionString

'msgbox sourceFile&NL&strPathToTextfile&NL&inputTemp&NL&tempFolder
adoCSVRecordset.Open "SELECT * FROM [" & tempFileName& "]", adoCSVConnection


confirmation=msgbox("Please verify the source and destination" & NL&NL & "Source: " &objfsob.getabsolutepathname(sourceFile)&NL&"Destination: "& outfilepath ,1)
if confirmation<>vbcancel then   

y=(countLines(objfsob.getabsolutepathname(sourceFile)))+1

set sourceFile=objFSOb.GetFile(sourcefile)

Dim objFSO,objTextFile,confirmation
Set objFSO = CreateObject("Scripting.FileSystemObject")
'msgbox outfilepath
Set objTextFile = objFSO.CreateTextFile(outfilepath, True)
 
if adoCSVRecordset.EOF=false then
   
   Dim vectors,tuples,setTuples,fieldCount,j,l,m

   'Stores all the data we want to know for the header info later on
   Dim fields()
   'fields(0) = name
   'fields(1) = min
   'fields(2) = max
   'fields(3) =   
   'fields(4) =
   'fields(5) =
   vectors=1
   tuples=0
   'Used through only one row of data to find out which columns to keep
   setTuples=true
   fieldCount=0

   dim ans1,arraydata,secs
   'ans1 is for debugging output panels
   ans1=vbok
   'accumlate time for each output data in logworks
   secs=0

   ' Read the CSV rows.
   do Until adoCSVRecordset.EOF
     ' Progress(2)
      x=x+1
      if vectors mod 500 = 0 then
         Sleep(1)
      end if
      if KeepGoing = false or window.screenTop > 10000 then            
            return
      end if
       tuples=0
       ' Display all fields by name.
       objTextFile.Writeline(BOT_LINE_STR)       
       objTextFile.Writeline(NUM_TYPE & SEP & secs)
       objTextFile.Writeline(VALID)
       'accumlate the next time entry
       secs=secs + ENTRY_RESOLUTION
       'loop through the columns
       for k = 0 To adoCSVRecordset.Fields.Count - 1
         'only take columns that are not empty, for now it requires all rows to at least have some data
         'So if the first row is full and the second row has a blank, it will break, fun.
          If adoCSVRecordset.Fields(k).Value <> "" and InStr(IGNORE_STR,adoCSVRecordset.Fields(k).Name)=0 then
            'resize the field array only if we haven't done a row yet
             If setTuples Then
                ReDim preserve fields(3,tuples)
                fields(0,tuples)=adoCSVRecordset.Fields(k).name                               
             End If

               'set our mininum for the column, yes this is horrid
             if fields(1,tuples)="" or adoCSVRecordset.Fields(k).Value < fields(1,tuples) Then
                'if ans1=vbok then
                  'ans1=msgbox(adoCSVRecordset.Fields(k).Value &"<"& fields(1,tuples),1)
                'end if
                fields(1,tuples)=adoCSVRecordset.Fields(k).Value
             End If
            
               'set our maximum for the column, yes this is horrid
             if fields(2,tuples)="" or adoCSVRecordset.Fields(k).Value > fields(2,tuples) Then
                'if ans1=vbok then
                  'ans1=msgbox(adoCSVRecordset.Fields(k).Value &">"& fields(2,tuples),1)
                'end if
                fields(2,tuples)=adoCSVRecordset.Fields(k).Value
             End If
            'reset arraydata, this is to print summary info
            'arraydata=""              
'           for j=0 to ubound(fields,1)
'              for l=0 to ubound(fields,2)
'                    arraydata= arraydata& j & "," & l &"=" & fields(j,l) &NL
'              next
'           next

            'write out the actual data
            objTextFile.Writeline(NUM_TYPE & SEP & adoCSVRecordset.Fields(k).Value)
            objTextFile.Writeline(VALID)
            'increment our row
            tuples=tuples+1
          end if          
       Next 'end loop of columns
       setTuples=false
       'increment the lines
       vectors = vectors+1
       adoCSVRecordset.MoveNext
   Loop 'end loop of rows
   Progress(0)
end if

'print the summary of the field data
'if ans1=vbok then
'  ans1=msgbox(arraydata,1)
'end if

' Clean up.
objTextFile.Close

'reopen the file to append header information
Set objTextFile = objFSO.OpenTextFile(outfilepath,1 )
Dim ReadAllTextFile
'store the previously written data that has no dif header info
ReadAllTextFile = objTextFile.ReadAll
objTextFile.Close
'reopen destination file for writing
Set objTextFile = objFSO.OpenTextFile(outfilepath,2,True)

'let's write some dif header info
objTextFile.Writeline(TABLE_STR)
objTextFile.Writeline("0,1")
objTextFile.Writeline("""EXCEL""")
objTextFile.Writeline(VECTORS_STR)
objTextFile.Writeline("0," & vectors+12)
objTextFile.Writeline(DBL_QT)
objTextFile.Writeline(TUPLES_STR)
objTextFile.Writeline("0," & tuples+1)
objTextFile.Writeline(DBL_QT)
objTextFile.Writeline(DATA_STR)
objTextFile.Writeline("0,0")
objTextFile.Writeline(DBL_QT)

'Write logworks header info
objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """Input Description""")
For k=1 to tuples
   objTextFile.Writeline(STR_TYPE_LINE)
   objTextFile.Writeline(DBL_QT)
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """Stochiometric:""")
For k=1 to tuples
   objTextFile.Writeline(STR_TYPE_LINE)
   objTextFile.Writeline(DBL_QT)
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """From Device:""")
For k=1 to tuples
   objTextFile.Writeline(STR_TYPE_LINE)
   objTextFile.Writeline("""(EVOSCAN"&k &")""")
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """Name:""")
For k=0 to ubound(fields,2)
   objTextFile.Writeline(STR_TYPE_LINE)
   objTextFile.Writeline(SIN_QT & fields(0,k)&SIN_QT )
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """Unit:""")
For k=0 to ubound(fields,2)
   objTextFile.Writeline(STR_TYPE_LINE)
   objTextFile.Writeline(SIN_QT & left(fields(0,k),3)&SIN_QT )
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """Range:""")
For k=0 to ubound(fields,2)   
   if fields(1,k) > 2 then
      fields(1,k)=fields(1,k)-2
   end if
   objTextFile.Writeline("0," & fix(fields(1,k)) )
   objTextFile.Writeline(VALID)
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """equiv(Sample):""")
For k=1 to tuples
   objTextFile.Writeline("0,0")
   objTextFile.Writeline(VALID)
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """to:""")
For k=0 to ubound(fields,2)   
   objTextFile.Writeline("0," & fix(fields(2,k))+1 )
   objTextFile.Writeline(VALID)
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """equiv(Sample):""")
For k=1 to tuples
   objTextFile.Writeline("0,4096")
   objTextFile.Writeline(VALID)
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """Color:""")
For k=0 to tuples-1
   objTextFile.Writeline("0,"& getFieldColor("test",k))
   objTextFile.Writeline(VALID)
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """-End-""")
For k=1 to tuples
   objTextFile.Writeline(STR_TYPE_LINE)
   objTextFile.Writeline(DBL_QT)
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """Session 1""")
For k=1 to tuples
   objTextFile.Writeline(STR_TYPE_LINE)
   objTextFile.Writeline(DBL_QT)
Next

objTextFile.Writeline(BOT_LINE_STR)
objTextFile.Writeline(STR_TYPE_LINE & NL & """Time(sec)""")
For k=0 to tuples-1
   objTextFile.Writeline(STR_TYPE_LINE)
   objTextFile.Writeline(SIN_QT & fields(0,k) & " (" & left(fields(0,k),3) & ")" & SIN_QT )
Next


'write out data we saved from before
'should consider a better way, won't scale with large files
objTextFile.Write(ReadAllTextFile)
objTextFile.Writeline("-1,0")
objTextFile.Writeline(EOD)

objTextFile.Close

'copy to a text file for easier debugging
'objFSO.CopyFile strPathToTextfile & "out.txt", strPathToTextfile & "out.dif"

adoCSVRecordset.Close
adoCSVConnection.Close
msgbox "Conversion completed successfully"
end if
else
        msgbox "You must choose an Evoscan file to convert..."
        Progress(0)
end if
else
   Progress(0)
end if
'subroutine to choose a color


end function

function getFieldColor(fieldName,fieldIdx)
   getFieldColor=colors(fieldIdx)
end function

 Function ChooseFile()
     Dim Result
     Dim IE : Set IE = CreateObject("InternetExplorer.Application")
     With IE
         .Visible = true
         .Navigate("about:blank")
         Do Until .ReadyState = 4 : Loop
         With .Document
             .Write "<html><body><input id='f' type='file'></body></html>"
             With .All.f
                 .Focus
                 .Click
                 Result = .Value
             End With
         End With
         .Quit
     End With
     Set IE = Nothing
    ChooseFile = Result
 End Function
 
Function countLines(strTextFile)

   Dim  txsInput, strTemp, arrLines
   CONST ForReading = 1
   Set objFSOt = CreateObject("Scripting.FileSystemObject")
   set myFile=objFSOt.GetFile(strTextFile)
   set txsInput=objFSOt.OpenTextFile(myFile,1)

   'Skip lines one by one 
   Do While txsInput.AtEndOfStream <> True
       strTemp = txsInput.SkipLine ' or .ReadLine
   Loop
   countLines = txsInput.Line-1 ' Returns the number of lines
   txsInput.close   
End Function


</script>
</head>
<body bgcolor="white">
<!-- Basic buttons -->
<input id="BtnGo"     type="button" value="Choose file to convert"     onclick="doit">
<input id="BtnCancel" type="button" value="Cancel" onclick="KeepGoing=False" disabled="True">
<input id="BtnExit"   type="button" value="Exit"   onclick="window.close">
<br>
<!-- Progress bar -->
Percent completed: <span id="ProgBarText">?</span><br>
<span id="ProgBarDone" style="background-color:blue"></span>
<span id="ProgBarToDo" style="background-color:silver"></span>

<!-- Progress bar (End) -->
<br/>
<br/>
<div>Windows 7 notes:</div>
<div>1) You must right click this program, select properties, and click "unblock."</div>
<div>2) You must ensure you have proper permissions to read/write the location of your saved datalogs.</div>
</body>
</html>
